<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/21
 * Time: 11:01
 */
namespace App\Service\Admin;

use App\Http\Model\Mysql\ShopModel;
use App\Utils\UploadAliOss;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;

class ShopService extends BaseService
{
    /**
     * 查看店铺列表
     * @param array $query  搜索条件
     * @param int $page  当前页码
     * @param int $size  每页数量
     * @return array
     */
    public function shopList(array $query = [], int $page = 1, int $size = 0)
    {
        $where['is_delete'] =   ShopModel::NOT_DELETE;
        /**
         * 搜索条件
         */
        if (isset($query['shop_name']) && !empty($query['shop_id'])) {
            $where[] =   ['shop_name', 'like', '%' . trim($query['shop_name']) . '%'];
        }

        if (isset($query['shop_contact']) && !empty($query['shop_contact'])) {
            $where['shop_contact']  =   trim($query['shop_contact']);
        }

        if (isset($query['shop_email']) && !empty($query['shop_email'])) {
            $where['shop_email']    =   trim($query['shop_email']);
        }

        $size   =   $size <= 0 ? self::PAGE_LIMIT : $size;
        $count  =   ShopModel::where($where)->count();

        $list   =   ShopModel::where($where)->select(['id', 'shop_name', 'shop_contact', 'shop_email', 'province', 'city', 'area', 'address', 'sorting', 'shop_logo', 'is_lock', 'is_open', 'updated_at'])
                    ->orderBy('sorting', 'desc')->limit($size)->offset(($page - 1) * $size)->get()->each(function (&$item) {
                        $item->update_time  =   $item->updated_at->toDateTimeString();
                        unset($item->updated_at);
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'current'=> $page,
                'pages'  => ceil($count / $size),
                'list'  =>  $list->toArray()
            ]];
        }
    }

    /**
     * 店铺添加
     * @param array $params 店铺信息参数
     * @return array
     */
    public function shopAdd(array $params = [])
    {
        $setting_path   =   Config::get('upload.local_path');
        $upload_path    =   public_path($setting_path);
        /**
         * 上传多图到本地
         */
        $logo_name      =   sha1($params['shop_logo']->getClientOriginalName() . createRandomNumber()) . '.' . $params['shop_logo']->extension();
        $pic_name       =   sha1($params['shop_pic']->getClientOriginalName() . createRandomNumber()) . '.' . $params['shop_pic']->extension();

        $params['shop_logo']->move($upload_path, $logo_name);
        $params['shop_pic']->move($upload_path, $pic_name);

        $upload[$logo_name] =    $upload_path . DIRECTORY_SEPARATOR . $logo_name;
        $upload[$pic_name]  =    $upload_path . DIRECTORY_SEPARATOR . $pic_name;

        /**
         * 上传多图到OSS服务器
         */
        $upload_ali_oss =   new UploadAliOss();
        [$flag, $result]=   $upload_ali_oss->uploadFile($upload);

        if ($flag) {
            /**
             * 删除本地图片
             */
            foreach ($upload as $item) {
                @unlink($item);
            }
        }

        $upload[$logo_name]     =   $result[$logo_name] ?? URL::asset($setting_path . '/' . $logo_name);
        $upload[$pic_name]      =   $result[$pic_name] ?? URL::asset($setting_path . '/' . $pic_name);

        $insert['shop_name']    =   $params['shop_name'];
        $insert['shop_contact'] =   $params['shop_contact'];
        $insert['shop_email']   =   $params['shop_email'] ?? '';
        $insert['shop_desc']    =   $params['shop_desc'] ?? '';
        $insert['unique_id']    =   createUniqueID();
        $insert['shop_logo']    =   $upload[$logo_name];
        $insert['shop_pic']     =   $upload[$pic_name];
        $insert['province']     =   $params['province'];
        $insert['city']         =   $params['city'];
        $insert['area']         =   $params['area'];
        $insert['address']      =   $params['address'];
        $insert['sorting']      =   $params['sorting'];
        $insert['is_open']      =   ShopModel::IS_OPEN;
        $insert['is_lock']      =   ShopModel::NOT_LOCK;
        $insert['is_live']      =   $params['is_live'];
        $insert['is_video']     =   $params['is_video'];
        $insert['is_short_video']=  $params['short_video'];
        $insert['auto_confirm_time']    =   $params['auto_confirm'];
        $insert['auto_cancel_time']     =   $params['auto_cancel'];
        $insert['auto_notify_time']     =   $params['auto_notify'];
        $insert['is_delete']    =   ShopModel::NOT_DELETE;
        $insert['apply_status'] =   ShopModel::APPLY_INIT;

        $insert_result  =   ShopModel::create($insert);
        if ($insert_result) {
            return [true, '添加成功'];
        } else {
            return [false, '添加失败'];
        }
    }

    /**
     * 店铺编辑
     * @param int $shop_id  店铺ID
     * @param array $params
     * @return array
     */
    public function shopEdit(int $shop_id, array $params = [])
    {
        $setting_path   =   Config::get('upload.local_path');
        $upload_path    =   public_path($setting_path);

        /**
         * 上传新图片
         */
        if (isset($params['shop_logo'])) {
            $logo_name          =   sha1($params['shop_logo']->getClientOriginalName() . createRandomNumber()) . '.' . $params['shop_logo']->extension();
            $params['shop_logo']->move($upload_path, $logo_name);

            $upload[$logo_name] =    $upload_path . DIRECTORY_SEPARATOR . $logo_name;
        }

        if (isset($params['shop_pic'])) {
            $icon_name           =   sha1($params['shop_pic']->getClientOriginalName() . createRandomNumber()) . '.' . $params['shop_pic']->extension();
            $params['shop_pic']->move($upload_path, $icon_name);

            $upload[$icon_name]  =    $upload_path . DIRECTORY_SEPARATOR . $icon_name;
        }


        /**
         * 上传多图到OSS服务器
         */
        if (!empty($upload)) {
            $upload_util    =   new UploadAliOss();
            [$flag, $result]=   $upload_util->uploadFile($upload);

            if ($flag) {
                /**
                 * 删除本地图片
                 */
                foreach ($upload as $item) {
                    @unlink($item);
                }
            }

            $update['shop_logo']   =  isset($params['brand_logo']) && isset($result[$logo_name]) ?? URL::asset($setting_path . '/' . $logo_name);
            $update['shop_pic']   =  isset($params['brand_icon']) && isset($result[$icon_name]) ?? URL::asset($setting_path . '/' . $icon_name);
        }

        $update['shop_name']    =   $params['shop_name'];
        $update['shop_contact'] =   $params['shop_contact'];
        $update['shop_email']   =   $params['shop_email'] ?? '';
        $update['shop_desc']    =   $params['shop_desc'] ?? '';
        $update['shop_name']    =   $params['shop_name'];
        $update['province']     =   $params['province'];
        $update['city']         =   $params['city'];
        $update['area']         =   $params['area'];
        $update['address']      =   $params['address'];
        $update['sorting']      =   $params['sorting'];
        $update['is_live']      =   $params['is_live'];
        $update['is_video']     =   $params['is_video'];
        $update['is_short_video']=  $params['short_video'];
        $update['auto_confirm_time']    =   $params['auto_confirm'];
        $update['auto_cancel_time']     =   $params['auto_cancel'];
        $update['auto_notify_time']     =   $params['auto_notify'];

        $update_result  =   ShopModel::where(['id' => $shop_id])->update($update);
        if ($update_result) {
            return [true, '修改成功'];
        }
        return [false, '修改失败'];
    }

    /**
     * 店铺详情
     * @param int $shop_id 店铺ID
     * @return array
     */
    public function shopInfo(int $shop_id)
    {
        $info   =   ShopModel::where(['id' => $shop_id, 'is_delete' => ShopModel::NOT_DELETE])->select(['id', 'shop_name', 'shop_desc', 'unique_id', 'shop_email', 'shop_desc', 'shop_logo', 'shop_pic', 'province', 'city', 'area', 'address',
                    'is_open', 'is_lock', 'is_live', 'is_video', 'is_short_video', 'sorting', 'auto_confirm_time', 'auto_cancel_time', 'auto_notify_time'])->first();
        if (empty($info)) {
            return [false, '暂无数据'];
        } else {
            return [true, $info];
        }
    }

    /**
     * 店铺删除
     * @param int $shop_id  店铺ID
     * @return array
     */
    public function shopDelete(int $shop_id)
    {
        $result =   ShopModel::where(['id' => $shop_id])->update(['is_delete' => ShopModel::IS_DELETE, 'delete_time' => Carbon::now()->timestamp]);

        if ($result) {
            return [true, '删除成功'];
        } else {
            return [false, '删除失败'];
        }
    }

    /**
     * 店铺审核
     * @param int $shop_id  店铺ID
     * @param int $apply_status 审核结果
     * @param string $apply_msg 审核信息
     * @return array
     */
    public function shopVerify(int $shop_id, int $apply_status, string $apply_msg = '')
    {
        $result =   ShopModel::where(['id' => $shop_id])->update(['apply_status' => $apply_status, 'apply_result' => $apply_msg]);
        if ($result) {
            return [true, '操作成功'];
        } else {
            return [false, '操作失败'];
        }
    }

    /**
     * 店铺锁定 (只能浏览，不能购买)
     * @param int $shop_id  店铺ID
     * @return array
     */
    public function shopLock(int $shop_id)
    {
        $result =   ShopModel::where(['id' => $shop_id])->update(['is_lock' => ShopModel::IS_LOCK]);
        if ($result) {
            return [true, '锁定成功'];
        } else {
            return [false, '锁定失败'];
        }
    }

}
